<template>
  <page-header-wrapper :title="false">
    <a-card
      title="微信管理"
    >
      <div slot="extra">
        <a-button style="margin-right:5px" type="danger" @click="onStatModal">
          统计
        </a-button>
        <a-button type="primary" data-edit="false" @click="batchModal">
          <a-icon type="plus"></a-icon>
          添加微信
        </a-button>
      </div>
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="60">
            <!--              <a-col :md="6" :sm="24">-->
            <!--                <a-form-model-item label="组长姓名">-->
            <!--                  <a-select-->
            <!--                    show-search-->
            <!--                    v-model="queryParam['lid']"-->
            <!--                    placeholder="选择组长姓名"-->
            <!--                    :filter-option="filterOption"-->
            <!--                  >-->
            <!--                    <a-select-option v-for="(item,index) in adviserOpts" :key="index" :value="index">{{item}}</a-select-option>-->
            <!--                  </a-select>-->
            <!--                </a-form-model-item>-->
            <!--              </a-col>-->
            <!--              <a-col :md="6" :sm="24">-->
            <!--                <a-form-model-item label="顾问姓名">-->
            <!--                  <a-select-->
            <!--                    show-search-->
            <!--                    v-model="queryParam['filter[uid]']"-->
            <!--                    placeholder="选择顾问姓名"-->
            <!--                    :filter-option="filterOption"-->
            <!--                  >-->
            <!--                    <a-select-option v-for="(item,index) in adviserOpts" :key="index" :value="index">{{item}}</a-select-option>-->
            <!--                  </a-select>-->
            <!--                </a-form-model-item>-->
            <!--              </a-col>-->
            <a-col :md="6" :sm="24">
              <a-form-model-item label="微信账号">
                <a-input v-model="queryParam['filter[wx_account]']" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="绑定手机号">
                <a-input v-model="queryParam['filter[phone]']" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <s-table
        bordered
        ref="table"
        :row-key="(record) => record.id"
        :columns="wxColumns"
        :data="wxData"
      >
        <template slot="wx_index" slot-scope="text, record, index">
          {{ index + 1 }}
        </template>
        <template slot="created_at" slot-scope="text">
          {{ text * 1000 | moment }}
        </template>
        <template slot="image2" slot-scope="text, record">
          <a v-if="record.image2" @click="handlePreview(record.image2)">
            <img :src="record.image2" width="30" height="30" />
          </a>
          <div v-else>无</div>
        </template>
        <template slot="image" slot-scope="text, record">
          <a @click="handlePreview(record.image)">
            <img :src="record.image" width="30" height="30" />
          </a>
        </template>
        <div
          slot="filterDropdown"
          slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          style="padding: 8px"
        >
          <a-input
            v-ant-ref="c => (searchInput = c)"
            :placeholder="`筛选${column.title}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block;"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
          />
          <a-button
            type="primary"
            icon="search"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            筛选
          </a-button>
          <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
            重置
          </a-button>
        </div>
        <template slot="sign" slot-scope="text, record">
          <div v-if="record.v_id != ''">
            <div v-if="record.yc_sign == 1">
              <a-rate :value="1" :count="1" :style="{ color: '#f00' }">
                <a-icon slot="character" type="exclamation-circle" />
              </a-rate>
            </div>
            <div v-else>
              <a-rate :value="0" :count="1" :style="{ color: '#f00' }">
                <a-icon slot="character" type="exclamation-circle" />
              </a-rate>
            </div>
          </div>
          <div v-else>
            <a-rate :value="0" :count="1" :style="{ color: '#f00' }">
              <a-icon slot="character" type="exclamation-circle" />
            </a-rate>
          </div>
        </template>
        <div slot="action" slot-scope="text, record">
          <a-button size="small" type="primary" @click="editModal(record.id)" style="margin-right: 10px;">编辑</a-button>
          <!--            <a-button size="small" type="primary" @click="remarkModal(record)" style="margin-right: 10px;">查看备注</a-button>-->
        </div>
      </s-table>
    </a-card>
    <a-modal
      title="添加微信"
      v-model="visible2"
      width="700px"
      @ok="onSubmit"
    >
      <a-form-model
        ref="dynamicValidateForm"
        :model="dynamicValidateForm"
      >
        <a-spin :spinning="formLoading">
          <a-row :gutter="10" v-for="(item, index) in dynamicValidateForm.wechat" :key="index">
            <a-col :span="5">
              <a-form-model-item
                :prop="'wechat.' + index + '.wx_account'"
                :rules="{
                  required: true,
                  message: '必须填写微信ID',
                  trigger: 'blur'
                }"
              >
                <a-input
                  v-model="dynamicValidateForm.wechat[index].wx_account"
                  type="text"
                  placeholder="填写微信ID"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="5">
              <a-form-model-item
                :prop="'wechat.' + index + '.phone'"
                :rules="[
                  { required: true, message: '必须填写联系电话', trigger: 'blur' },
                  { len: 11, message: '手机必须是11位', trigger: 'blur' },
                  { pattern: /^1[3-9]{1}[0-9]{9}$/, message: '手机号码不正确', trigger: 'blur' }
                ]"
              >
                <a-input
                  v-model="dynamicValidateForm.wechat[index].phone"
                  type="text"
                  placeholder="必须填写联系电话"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="5">
              <a-form-model-item
                :prop="'wechat.' + index + '.image'"
                :rules="[
                  { required: true, message: '必须上传聊天截图', trigger: 'change' }
                ]"
              >
                <a-upload
                  name="file"
                  :headers="headers"
                  :action="upload"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                  @change="info => batchImage(info, index)"
                >
                  <a-button style="width:100%" :disabled="dynamicValidateForm.wechat[index].image !== ''">
                    <a-icon type="upload" />
                    {{ dynamicValidateForm.wechat[index].image !== '' ? '已上传' : '确认截图' }}
                    <!--                    <span v-if="item.image">-->
                    <!--                      <ellipsis :length="8">{{dynamicValidateForm.wechat[index].image}}</ellipsis>-->
                    <!--                    </span>-->
                    <!--                    <span v-else>-->
                    <!--                      选择截图-->
                    <!--                    </span>-->
                  </a-button>
                </a-upload>
                <!--                <a-button type="primary" style="margin-left: 10px" :disabled="dynamicValidateForm.wechat[index].image">上传</a-button>-->
              </a-form-model-item>
            </a-col>
            <a-col :span="9">
              <a-form-model-item
                :prop="'wechat.' + index + '.image2'"
                :rules="[
                  { required: true, message: '必须上传客户账号截图', trigger: 'change' }
                ]"
              >
                <a-row :gutter="20">
                  <a-col :span="12">
                    <a-upload
                      name="file"
                      :headers="headers"
                      :action="upload"
                      :show-upload-list="false"
                      :before-upload="beforeUpload"
                      @change="info => batchImage2(info, index)"
                    >
                      <a-button block :disabled="dynamicValidateForm.wechat[index].image2 != ''">
                        <a-icon type="upload" />
                        {{ dynamicValidateForm.wechat[index].image2 != '' ? '已上传' : '账号截图' }}
                      </a-button>
                    </a-upload>
                  </a-col>
                  <a-col :span="6">
                    <a-button :disabled="dynamicValidateForm.wechat[index].image == '' || dynamicValidateForm.wechat[index].image2 == ''" type="danger" @click="delImage(index)">删除</a-button>
                  </a-col>
                  <a-col :offset="2" :span="4">
                    <a-icon
                      v-if="dynamicValidateForm.wechat.length > 1"
                      class="dynamic-delete-button"
                      type="minus-circle-o"
                      :disabled="dynamicValidateForm.wechat.length === 1"
                      @click="removeInput(item)"
                    />
                  </a-col>
                </a-row>
                <!--                <a-button type="primary" style="margin-left: 10px" :disabled="dynamicValidateForm.wechat[index].image">上传</a-button>-->
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-spin>
        <a-form-model-item>
          <a-button type="dashed" v-if="dynamicValidateForm.wechat.length < 8" @click="addInput">
            <a-icon type="plus" /> 增加输入框
          </a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-alert
            message="警告"
            description="假如出现假的微信号，一旦组长核实完毕，一条微信扣款200元，请慎重添加"
            type="warning"
            show-icon
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      title="编辑微信"
      v-model="visible"
      @ok="onEdit"
      @cancel="cancelModal"
    >
      <a-form-model
        ref="addForm"
        :rules="addRule"
        :model="addForm"
      >
        <a-form-model-item prop="image2">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :headers="headers"
            :action="upload"
            @change="handleImage2"
          >
            <img v-if="addForm.image2" :src="addForm.image2" width="100" height="100" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传微信截图
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item prop="image">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :headers="headers"
            :action="upload"
            @change="handleImage"
          >
            <img v-if="addForm.image" :src="addForm.image" width="100" height="100" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传微信截图
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="微信号码（ID）" prop="wx_account">
          <a-input v-model="addForm.wx_account" type="text" placeholder="输入客户微信号码" />
        </a-form-model-item>
        <a-form-model-item label="手机号码">
          <a-input v-model="addForm.phone" type="text" placeholder="手机联系号码" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      title="统计总览"
      :width="600"
      v-model="visible3"
    >
      <a-row :gutter="[0, 50]">
        <a-col :span="24">
          <a-row :gutter="20">
            <a-col :span="8">
              <a-card>
                <a-statistic
                  title="微信总数"
                  :value="wxStat.wx_sum"
                  :precision="0"
                >
                </a-statistic>
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card v-if="wxStat.wx_today > wxStat.wx_yesterday">
                <a-statistic
                  title="今日添加"
                  :value="wxStat.wx_today"
                  :value-style="{ color: '#3f8600' }"
                >
                  <template #prefix>
                    <a-icon :style="{ fontSize: '14px' }" type="arrow-up" />
                  </template>
                </a-statistic>
              </a-card>
              <a-card v-else>
                <a-statistic
                  title="今日添加"
                  :value="wxStat.wx_today"
                  :value-style="{ color: '#cf1322' }"
                >
                  <template #prefix>
                    <a-icon :style="{ fontSize: '14px' }" type="arrow-down" />
                  </template>
                </a-statistic>
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card>
                <a-statistic
                  title="昨日添加"
                  :value="wxStat.wx_yesterday"
                >
                </a-statistic>
              </a-card>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="24">
          <h4 :style="{ marginBottom: '20px' }">近10天</h4>
          <a-divider></a-divider>
          <v-chart
            height="200"
            :data="barData"
            :forceFit="true"
            :padding="['auto', 'auto', '40', 'auto']"
          >
            <v-tooltip :shared="true"/>
            <v-axis/>
            <v-interval position="x*y" :opcaity="1"></v-interval>
          </v-chart>
        </a-col>
      </a-row>
    </a-modal>
    <a-modal
      title="查看评价"
      v-model="remarkVisible"
      :footer="null"
    >
      <a-comment>
        <a slot="author">{{ content.author }}</a>
        <a-avatar
          slot="avatar"
          icon="user"
        />
        <p slot="content">
          {{ content.remark }}
        </p>
      </a-comment>
    </a-modal>
    <a-modal v-model="previewVisible" :footer="null" @cancel="handleCancel0">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </page-header-wrapper>
</template>

<script>
  import storage from 'store'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { STable, Ellipsis } from '@/components'
  import { getWeixin, getAddWx, subEditWx, getEditWx, postAddWx, getWxData } from '@/api/customer'
  import custCol from '@/columns/customer'
  import apis from '@/api'
  const wxColumns = custCol.wx
  export default {
    components: {
      STable,
      Ellipsis
    },
    name: 'Wechat',
    data () {
      return {
        barData: [],
        wxColumns,
        wxData: parameters => {
          return getWeixin(Object.assign(parameters, this.queryParam)).then(res => {
            return res.result
          })
        },
        // advanced: true,
        wid: 0,
        loading: false,
        formLoading: false,
        dynamicValidateForm: {
          wechat: []
        },
        addForm: {
          image2: '',
          image: '',
          phone: '',
          wx_account: ''
        },
        addRule: {
          image2: [
            { required: true, message: '上传微信账号截图', trigger: 'change' }
          ],
          image: [
            { required: true, message: '上传客户微信截图', trigger: 'change' }
          ],
          wx_account: [
            { required: true, message: '填写客户微信号', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '填写手机号码', trigger: 'blur' },
            { pattern: /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/, message: '请输入正确的手机号', trigger: 'blur' },
            { len: 11, message: '手机号码应为11位', trigger: 'blur' }
          ]
        },
        visible: false,
        visible2: false,
        visible3: false,
        upload: apis.Upload,
        wxStat: {},
        headers: {
          'access-token': storage.get(ACCESS_TOKEN)
        },
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
        queryParam: {},
        searchText: '',
        remarkVisible: false,
        content: {},
        previewImage: '',
        previewVisible: false
      }
    },
    methods: {
      addInput () {
        const app = this
        if (app.dynamicValidateForm.wechat.length < 10) {
          app.dynamicValidateForm.wechat.push({
            wx_account: '',
            phone: '',
            image: '',
            image2: ''
          })
        } else {
          app.$warning({
            title: '最多允许添加10个'
          })
        }
      },
      async handlePreview (file) {
        this.previewImage = file
        this.previewVisible = true
      },
      handleCancel0 ({ fileList }) {
        this.fileList = fileList
      },
      remarkModal (item) {
        if (item.remark !== '') {
          this.content['author'] = item.r_author
          this.content['remark'] = item.remark
          this.remarkVisible = true
        } else {
          this.$warning({
            title: '暂无备注内容'
          })
        }
      },
      removeInput (item) {
        const index = this.dynamicValidateForm.wechat.indexOf(item)
        if (index !== -1) {
          this.dynamicValidateForm.wechat.splice(index, 1)
        }
      },
      addModal () {
        this.visible = true
      },
      batchModal () {
        this.visible2 = true
      },
      cancelModal () {
        this.visible = false
        this.wid = 0
        this.resetForm('addForm')
        this.$refs.table.refresh()
      },
      handleSearch (selectedKeys, confirm, dataIndex) {
        confirm()
        this.searchText = selectedKeys[0]
        this.searchedColumn = dataIndex
      },
      handleReset (clearFilters) {
        clearFilters()
        this.searchText = ''
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      onEdit () {
        const app = this
        const addForm = {}
        app.$refs.addForm.validate(valid => {
          if (valid) {
            getAddWx().then(res => {
              if (res.status === 0) {
                for (const k in app.addForm) {
                  addForm['wx[' + k + ']'] = app.addForm[k]
                }
                addForm.id = app.wid
                subEditWx(addForm).then(res => {
                  if (res.status === 0) {
                    app.visible = false
                    app.$refs.table.refresh()
                  } else {
                    app.$warning({
                      title: res.msg
                    })
                  }
                })
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          } else {
            return false
          }
        })
      },
      onSubmit () {
        const app = this
        const addForm = {}
        app.$refs.dynamicValidateForm.validate(valid => {
          if (valid) {
            app.formLoading = true
            for (let i = 0; i < app.dynamicValidateForm.wechat.length; i++) {
              getAddWx().then(res => {
                if (res.status === 0) {
                  const wechat = app.dynamicValidateForm.wechat[i]
                  for (const k in wechat) {
                    addForm['wx[' + k + ']'] = wechat[k]
                  }
                  postAddWx(addForm).then(add => {
                    if (add.status === 0) {
                      if ((i + 1) === app.dynamicValidateForm.wechat.length) {
                        app.formLoading = false
                        app.visible2 = false
                        app.$refs.table.refresh()
                      }
                    } else {
                      app.$warning({
                        title: add.msg
                      })
                      app.formLoading = false
                      return false
                    }
                  })
                }
              })
            }
          } else {
            return false
          }
        })
      },
      handleImage (info) {
        if (info.file.status !== 'uploading') {
          this.loading = true
        }
        if (info.file.status === 'done') {
          this.addForm.image = info.file.response.result.url
          this.loading = false
        }
      },
      handleImage2 (info) {
        if (info.file.status !== 'uploading') {
          this.loading = true
        }
        if (info.file.status === 'done') {
          this.addForm.image2 = info.file.response.result.url
          this.loading = false
        }
      },
      beforeUpload (file) {
        const app = this
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJpgOrPng) {
          app.$warning({
            title: '上传的图片格式不正确'
          })
        }
        if (!isLt2M) {
          app.$warning({
            title: '图片不能大于2MB'
          })
        }
        return isJpgOrPng && isLt2M
      },
      batchImage (info, index) {
        if (info.file.status === 'done') {
          this.dynamicValidateForm.wechat[index].image = info.file.response.result.url
        }
      },
      batchImage2 (info, index) {
        if (info.file.status === 'done') {
          this.dynamicValidateForm.wechat[index].image2 = info.file.response.result.url
        }
      },
      delImage (index) {
        const { dynamicValidateForm } = this
        dynamicValidateForm.wechat[index].image = ''
        dynamicValidateForm.wechat[index].image2 = ''
      },
      editModal (id) {
        const app = this
        app.visible = true
        app.wid = id
        getEditWx(app.wid).then(res => {
          if (res.status === 0) {
            app.addForm = res.result.wx
          }
        })
      },
      onStatModal () {
        getWxData().then(res => {
          if (res.status === 0) {
            this.wxStat = res.result
            for (const k in res.result.data) {
              this.barData.push({
                x: k,
                y: res.result.data[k]
              })
            }
            this.visible3 = true
          }
        })
      }
    }
  }
</script>

<style scoped>
  .message-type {
    margin-bottom: 20px;
  }
  .message-type button {
    margin-right: 5px;
  }
  .dynamic-delete-button {
    cursor: pointer;
    position: relative;
    top: 4px;
    font-size: 24px;
    color: #999;
    transition: all 0.3s;
  }
  .dynamic-delete-button:hover {
    color: #777;
  }
  .dynamic-delete-button[disabled] {
    cursor: not-allowed;
    opacity: 0.5;
  }
</style>
